package commons.base.rpc;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import commons.base.http.SimpleHttpClient;

public class MethodInvocationHandler implements InvocationHandler, Serializable {
   
	private static final long serialVersionUID = 1L;
	
    private String interfaceName; 
    private String url;

    public MethodInvocationHandler(String url, String interfaceName) {
        this.url = url;
        this.interfaceName = interfaceName;
    }

    public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
    	String fullUrl = url;
    	if(url.charAt(url.length() - 1) != '/'){
    		fullUrl += "/";
    	}
    	fullUrl += interfaceName + "/" + method.getName();
    			
    	String result = SimpleHttpClient
	        	.newPost(fullUrl)
	        	.setBodyString(JSON.toJSONString(args))
	        	.execute().getBody();

        return parseObject(result, interfaceName+"_"+method.getName()+"_response", method.getReturnType());
    }

	public <T> T parseObject(String text, String fieldName, Class<T> clazz){
		JSONObject json = JSON.parseObject(text);
		
		if(json.containsKey("error_response")){
			throw new RpcException(json.getString("error_response"));
		}
		
		if(json.containsKey(fieldName)){
			return JSON.toJavaObject(json.getJSONObject(fieldName), clazz);
		}
		
		throw new RpcException("illegal response: expect "+fieldName+" but " + text);
	}
}